import React from 'react';
import '../storeManage/addStore.less';
import region from '../../../common/region';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message, Tree, Cascader,Modal,DatePicker,Checkbox, Row, Col} from 'antd';
import moment from 'moment';
import $ from 'jquery';
import config from '../../../config/config';
const allRouter=config.router;
const privilegeData=config.gData;
const nations=config.nationData;
const { TextArea } = Input;
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
class AddEmployee extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            age:0,//计算年龄
            roleList:[],//角色列表
            visible2:false,//增加关联门店模态框
            storeNameList:[],//所有门店列表
            selectedStoreList:[],//已选择的门店列表把初始值赋值一份给保存
            initialSelectedStoreList:[],//保存最开始的已关联门店的初始值，如果模态框点击取消则不改变，如果点击确定，再把数据赋值
            visible1:false,//增加关联科室模态框
            departmentNameList:[],//所有科室列表
            selectedDepartmentList:[],//已选择的科室列表把初始值赋值一份给保存
            initialselectedDepartmentList:[],//保存最开始的已关联科室列表的初始值，如果模态框点击取消则不改变，如果点击确定，再把数据赋值
            tree: { name: '全部科室', keyword: '根' },//科室
            checkedKeys:[],//树形选择
            visible3:false,//增加权限模态框
            privilegeNameList:[],//所有权限
            selectedPrivilegeList:[],//已选择的权限列表把初始值赋值一份给保存
            initialPrivilegeList:[],//保存最开始的已关联权限列表的初始值，如果模态框点击取消则不改变，如果点击确定，再把数据赋值
            tree1: { name: '全部权限', keyword: '根' },//权限
            checkedKeys1:[],//树形选择
            alreadyChooseRole:false,//是否显示权限设置
            privilegeOfRole:[],//用来过滤该角色没有的权限
            justShowingStore:[],//只是为了展示，因为门店列表的数据为ID
            justShowingDepartment:[],//只是为了展示科室列表
            justShowingPrivilege:[],//只是为了展示权限列表
            isDoctorRole:false,//标志选择角色是否为医生，只有角色选择为医生，才显示科室权限
            canGetMoney:false,
            canGetMoneyByProject:false,
            handnamed:false,//标志是否重名
            isAlreadyChosedIdCard:false,//是否选择了证件类型，决定ID号码是否填写
        };
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
        this.getStoreList();
        this.getRolesList();
        this.getDepartmentsList();
        this.setState({
            privilegeNameList:privilegeData
        })
    }
    componentDidMount() {
        this.handleRegion();
        //如果为编辑状态
        if(this.props.params.employeeId != "0"){
            let url=allRouter.patientOrigin+'/doctor/one/'+this.props.params.employeeId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log("data::::");
                    console.log(data);
                    //把已经关联的门店赋值给到模态框显示，
                    // 把已经关联的科室赋值给到模态框显示，
                    if(data.code===200){
                        this.setState({
                            alreadyChooseRole:true,
                            selectedStoreList:data.user.shop,
                            initialselectedDepartmentList:data.user.department,
                            selectedDepartmentList:data.user.department,
                            checkedKeys:data.user.department,
                            selectedPrivilegeList:data.user.jurisdiction,
                            checkedKeys1:data.user.jurisdiction,
                            initialPrivilegeList:data.user.jurisdiction,
                            privilegeOfRole:[],
                        },()=>{
                            this.changeToWord(this.state.selectedStoreList);
                            this.changeToWord1(this.state.selectedDepartmentList);
                            this.changeToWord2(this.state.selectedPrivilegeList);
                        });
                        //保存最开始的已关联门店的初始值
                        let initName=[];
                        data.user.shop.map(item=>{
                            initName.push(item);
                        });
                        this.setState({
                            initialSelectedStoreList:initName
                        });
                        let values=data.user;
                       if(values.commissiontype){
                           this.handleChangeGetMoneyType(values.commissiontype);
                       }
                        this.setState({
                            isAlreadyChosedIdCard:false
                        });
                        if(values.papers){
                            this.setState({
                                isAlreadyChosedIdCard:true
                            })
                        }
                        if(values.birthday){
                            // console.log(1111);
                            this.calculateAge(moment(values.birthday));
                        }
                        this.state.roleList.map(item=>{
                            // console.log(item);
                            if(item.value==values.role){
                                this.setState({
                                    privilegeOfRole:item.tree,
                                });
                                if(item.label==="医生"){
                                    this.setState({
                                        isDoctorRole:true,
                                    })
                                }
                            }
                        });
                        this.setState({
                            selectedStoreList:values.shop
                        },()=>{
                            this.changeToWord(this.state.selectedStoreList);
                        });
                        this.props.form.setFieldsValue({
                            username:values.name,
                            gender:values.sex,
                            birthday:values.birthday? moment(values.birthday) : undefined,
                            phone:values.phone,
                            positionAttribution:values.post,
                            belongedRole:[values.role],
                            // department:[],//关联科室
                            // shop:[],//关联门店
                            // jurisdiction:[],//权限
                            bonusType:values.commissiontype,
                            projectBonus1:values.commissionproject.split('&')[0],
                            projectBonus2:values.commissionproject.split('&')[1],
                            projectBonus3:values.commissionproject.split('&')[2],
                            bonusScale:values.commissionratio,
                            isMarried:values.marriage,
                            nation:values.nation,
                            email:values.email,
                            cardType:values.papers,
                            identification:values.IDcard,
                            introduction:values.synopsis,
                            password:values.password,
                            confirmPassword:values.password,
                            uname:values.phone,
                        });
                    }else{
                        console.log("获取患者来源名称出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }else{
            //这是新增员工，默认关联该登录员工的门店,默认勾选，不可取消勾选
            this.setState({
                selectedStoreList:JSON.parse(sessionStorage.getItem('UserInfo')).shop,
                initialSelectedStoreList:JSON.parse(sessionStorage.getItem('UserInfo')).shop,
            },()=>{
                this.changeToWord(this.state.selectedStoreList);
            })
        }
    }
    //处理省市区数据
    handleRegion() {
        const setOptions = arr => {
            arr.map((item, key) => {
                item.value = item.name;
                item.label = item.name;
                if (item.child) {
                    item.children = item.child;
                    setOptions(item.children);
                }
            });
        };
        setOptions(region);
        this.setState({
            region
        });
    }
    //生日禁用
    disabledDate(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }
    //获取角色列表
    getRolesList() {
        let url=allRouter.patientOrigin+'/role/list';
        if(!this.state.Inkey){
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:res=>{
                    let roles=[];
                    const rolesList = res.roles;
                    if (rolesList.length > 0) {
                        rolesList.forEach((ele, i) => {
                            if(ele.name==="超级管理员"){
                                roles.push({ value: ele._id, disabled: true,label: ele.name,tree:ele.tree});
                            }else{
                                if(ele.state==="禁用"){
                                    roles.push({ value: ele._id, disabled: true, label: '(已失效)'+ele.name,tree:ele.tree});
                                }else{
                                    roles.push({ value: ele._id, label: ele.name,tree:ele.tree});
                                }

                            }
                        });
                    }
                    console.log('角色列表');
                    console.log(roles);
                    this.setState({
                        roleList:roles
                    })
                },
                error:err=>{
                    message.config({ top: 80, });
                    message.error('获取角色列表失败，请返回重新操作', 2);
                }
            });
        }
    }
    //获取门店列表
    getStoreList() {
        let url=allRouter.patientOrigin+'/cmmuseum/list';
        //console.log(url);
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    if (data.cmmuseums.length > 0) {
                        data.cmmuseums.forEach((ele, i) => {
                            ele.index= i + 1;
                        });
                    }
                    this.setState({
                        storeNameList:data.cmmuseums.filter(key=>key.state!=="禁用")
                    })
                }else{
                    console.log("获取门店列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //获取科室列表
    getDepartmentsList() {
        let url=allRouter.patientOrigin+'/department/list';
        //console.log(url);
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log("科室：");
                console.log(data);
                if(data.code===200){
                    //给列表每一项增加索引
                    if (data.department.length > 0) {
                        data.department.map((item,i) => {
                            item.index=i+1;
                            item.mySon=[];
                            item.keyword=item.name;
                            item.key=item._id;
                            if (item.son.length) {
                                item.son.map((itemSon,i)=>{
                                    data.department.map((item1,i)=>{
                                        if(itemSon===item1._id){
                                            item.mySon.push(item1);
                                        }
                                    })
                                })
                            }
                        });
                    }
                    console.log("科室：");
                    console.log(data);
                    this.setState({
                        departmentNameList:data.department.filter(key=>key.state!=="禁用")
                    },()=>{
                        console.log(this.state.departmentNameList);
                    })
                }else{
                    console.log("获取科室列表列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //保存员工
    saveData(){
        this.props.form.validateFields((err,fieldsValue)=> {
            //  console.log(fieldsValue);
            if (!err) {
                if (fieldsValue.password != fieldsValue.confirmPassword) {
                    // return this.props.form.setFields({
                    //     password: {value: fieldsValue.password, errors: '两次输入的密码不一致，请再次输入'},
                    //     confirmPassword: {value: fieldsValue.confirmPassword, errors: '两次输入的密码不一致，请再次输入'},
                    // })
                    message.info('两次输入的密码不一致，请再次输入',2);
                    return;
                }
                if(this.state.handnamed){
                    message.error('该员工电话号码已经存在!',1);
                    return;
                }
                const values = {
                    ...fieldsValue,
                    'birthday': fieldsValue['birthday']?fieldsValue['birthday'].format('YYYY-MM-DD'):'',
                };
                console.log(values);
                console.log('测试数据');
                let role='';
                this.state.roleList.map(item=>{
                    if(item.value===values.belongedRole[0]){
                        role=item.label;
                    }
                });
                if(role==='医生'){
                    if(!this.state.selectedDepartmentList.length){
                        message.info('该医生未关联科室');
                        return;
                    }
                    if(this.state.selectedDepartmentList.length!==1){
                        message.info('该医生暂时只能关联一个科室');
                        return;
                    }
                    if(this.state.selectedDepartmentList.length===1&&this.state.selectedDepartmentList[0]==="全部科室"){
                        console.log(111111);
                        message.info('该医生未关联科室');
                        return;
                    }
                }
                if(!this.state.initialSelectedStoreList.length){
                    message.info('该员工未关联门店');
                    return;
                }
                if(!this.state.selectedPrivilegeList.length){
                    message.info('该员工未设置权限');
                    return;
                }
                console.log(this.state.selectedDepartmentList);
                console.log(this.state.initialSelectedStoreList);
                console.log(this.state.selectedPrivilegeList);

                //即是编辑状态  无状态更新 不能修改密码，不传密码,需要传递ID
                if(this.props.params.employeeId != "0"){
                    Modal.confirm({
                        title: '修改员工信息',
                        className:'confirm-error',
                        content: '操作提醒！修改之后该员工可能需要重新登录。',
                        onCancel: () => { },
                        onOk: () => {
                            let url=allRouter.patientOrigin+'/doctor/update';
                            // console.log(url);
                            $.ajax({
                                url: url,
                                type: "post",
                                async: true,
                                traditional: true,
                                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                                data: {
                                    id:this.props.params.employeeId,
                                    name:values.username,
                                    sex:values.gender,
                                    birthday:values.birthday,
                                    phone:values.phone,
                                    post:values.positionAttribution,
                                    role:values.belongedRole,
                                    department:this.state.selectedDepartmentList,//关联科室
                                    shop:this.state.initialSelectedStoreList,//关联门店
                                    jurisdiction:this.state.selectedPrivilegeList,//权限
                                    commissiontype:values.bonusType,
                                    commissionproject:(!values.projectBonus1?0:values.projectBonus1)+'&'+(!values.projectBonus2?0:values.projectBonus2)+'&'+(!values.projectBonus3?0:values.projectBonus3),
                                    commissionratio:values.bonusScale,
                                    marriage:values.isMarried,
                                    nation:values.nation,
                                    email:values.email,
                                    papers:values.cardType,
                                    IDcard:values.identification,
                                    synopsis:values.introduction,
                                },
                                success:data => {
                                    //  console.log(data);
                                    if(data.code===200){
                                        message.info('员工信息修改成功',);
                                        browserHistory.push('employeeManage');
                                    }
                                },
                                error:err=>{
                                    console.log(err);
                                }
                            });
                        }
                    });
                }else{
                    // 即是新增状态
                    let url=allRouter.patientOrigin+'/doctor/save';
                    $.ajax({
                        url: url,
                        type: "post",
                        async: true,
                        traditional: true,
                        headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                        data: {
                            name:values.username,
                            sex:values.gender,
                            birthday:values.birthday,
                            phone:values.phone,
                            post:values.positionAttribution,
                            role:values.belongedRole,
                            department:this.state.selectedDepartmentList,//关联科室
                            shop:this.state.initialSelectedStoreList,//关联门店
                            jurisdiction:this.state.selectedPrivilegeList,//权限
                            commissiontype:values.bonusType,
                            commissionproject:(!values.projectBonus1?0:values.projectBonus1)+'&'+(!values.projectBonus2?0:values.projectBonus2)+'&'+(!values.projectBonus3?0:values.projectBonus3),
                            commissionratio:values.bonusScale,
                            marriage:values.isMarried,
                            nation:values.nation,
                            email:values.email,
                            papers:values.cardType,
                            IDcard:values.identification,
                            synopsis:values.introduction,
                            password:values.password,
                            state:'启用'
                        },
                        success:data => {
                            console.log('员工返回的信息');
                            console.log(data);
                            if(data.code===200){
                                message.info('员工增加成功',);
                                browserHistory.push('employeeManage');

                            }else if(data.code===201){
                                message.error('员工用户名已存在，请修改');
                            }else{
                                message.info('员工增加失败');
                            }
                        },
                        error:err=>{
                            console.log(err);
                        }
                    });
                }
            }
            // browserHistory.push('employeeManage');
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回员工列表页面吗？',
            onCancel:()=>{console.log('取消')},
            onOk:()=>{
                browserHistory.push('employeeManage');
            }
        })
    }

    //显示关联科室模态框
    showModal1() {
        this.setState({
            visible1: true,
        });
    }
    //关联所属科室
    handleOk1() {
        console.log(this.state.checkedKeys);
        if(this.state.checkedKeys.length===0){
            this.setState({
                justShowingDepartment:[]
            })
        }
        this.setState({
            visible1: false,
            selectedDepartmentList:this.state.checkedKeys
        },()=>{
            // console.log('打印在选择的时候改变的数组');
            // console.log(this.state.selectedDepartmentList);
            this.changeToWord1(this.state.selectedDepartmentList);
        })
    }
    //取消关联所属科室
    handleCancel1() {
        this.setState({
            visible1: false,
            selectedDepartmentList:this.state.initialselectedDepartmentList
        },()=>{
            this.changeToWord1(this.state.selectedDepartmentList);
        });
    }
    //tree树形变化函数
    onCheckDepartment(checkedKeys, e) {
        console.log(checkedKeys);
        this.setState({
            checkedKeys,
        });
    }

    //显示关联门店模态框
    showModal2() {
        this.setState({
            visible2: true,
        });
    }
    //关联所属门店
    handleOk2() {
        // console.log(this.state.selectedStoreList);
        // console.log(typeof(this.state.selectedStoreList));
        this.setState({
            initialSelectedStoreList:this.state.selectedStoreList,
            visible2: false,
        },()=>{
            // console.log(this.state.initialSelectedStoreList);
            // console.log(typeof(this.state.initialSelectedStoreList));
        })
    }
    //取消关联所属门店
    handleCancel2() {
        this.setState({
            visible2: false,
            selectedStoreList:this.state.initialSelectedStoreList
        },()=>{
            this.changeToWord(this.state.selectedStoreList);
        });
    }
    //所属门店模态框变化函数
    handleBelongedStoreChange(checkedValues){
        console.log(checkedValues);
        if(checkedValues.length===0){
            this.setState({
                justShowingStore:[],
            })
        }
        //console.log(checkedValues);
        this.setState({
            selectedStoreList:checkedValues
        },()=>{
            this.changeToWord(this.state.selectedStoreList);
        })
    }
    //显示权限模态框
    showModal3() {
        this.setState({
            visible3: true,
        });
    }
    //权限模态框确定
    handleOk3() {
        this.setState({
            visible3: false,
            selectedPrivilegeList:this.state.checkedKeys1
        },()=>{
            //  console.log('打印在选择的时候改变的数组33333');
            // console.log(this.state.selectedPrivilegeList);
            this.changeToWord2(this.state.selectedPrivilegeList);
        })
    }
    //取消权限模态框
    handleCancel3() {
        this.setState({
            visible3: false,
            selectedPrivilegeList:this.state.initialPrivilegeList
        },()=>{
            this.changeToWord2(this.state.selectedPrivilegeList);
        });
    }
    //tree树形变化函数
    onCheckPrivilege1(checkedKeys1, e) {
        // console.log(checkedKeys1);
        this.setState({
            checkedKeys1,
        });
    }
    //绑定手机号输入框的onChange事件，设置用户名
    changUserName(e){
        // console.log(e.target.value);
        this.props.form.setFieldsValue({
            uname: e.target.value
        })
    }
    //选择日期，计算年龄
    calculateAge(date, dateString){
        if(date){
            let bornYear=date.format('YYYY');
            // console.log(bornYear);
            let currentYear=new Date().getFullYear();
            this.setState({
                age:currentYear-bornYear
            })
        }else{
            this.setState({
                age:0,
            })
        }
    }
    //选择角色，改变权限设置
    handleRoleChange(value){
        console.log(value);
        console.log(this.state.roleList);
        this.setState({
            alreadyChooseRole:true,
            // selectedPrivilegeList:[],
            // checkedKeys1:[]
        },()=>{
            // this.changeToWord2(this.state.selectedPrivilegeList);
        });
        this.state.roleList.map(item=>{
            if(item.value==value){
                //只有角色为医生的才显示科室
                if(item.label==='医生'){
                    this.setState({
                        isDoctorRole:true,
                    })
                }else{
                    this.setState({
                        isDoctorRole:false,
                    })
                }
                this.setState({
                    privilegeOfRole:item.tree,
                    selectedPrivilegeList:item.tree,
                    checkedKeys1:item.tree,
                },()=>{
                    this.changeToWord2(item.tree);
                    // console.log(this.state.checkedKeys1);
                })
            }
        })
    }

    //验证名称是否重复
    hadnamed(e){
        // console.log(e.target.value);
        let scheduleName = e.target.value
        let url=allRouter.patientOrigin+'/doctor/alreadyregister';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                phone:e.target.value
            },
            success:data => {
                //  console.log(data);
                if(data.code===201){
                    this.props.form.setFields({
                        phone: { value: scheduleName,errors: [new Error(data.mes)] }
                    })
                    this.setState({
                        handnamed:true
                    })
                }else{
                    this.setState({
                        handnamed:false
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }

    //把ID转换成汉字显示 门店
    changeToWord(selectedStore){
        console.log(selectedStore);
        let justShowingStore=[];
        let storeNameList1=[];
        if(selectedStore.length){
            if(this.state.storeNameList.length===0){
                let url=allRouter.patientOrigin+'/cmmuseum/list';
                $.ajax({
                    url:url,
                    type: "GET",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    success:data=>{
                        if(data.code===200){
                            if (data.cmmuseums.length > 0) {
                                data.cmmuseums.forEach((ele, i) => {
                                    ele.index= i + 1;
                                });
                            }
                            storeNameList1=data.cmmuseums.filter(key=>key.state!=="禁用");
                            if(selectedStore.length){
                                selectedStore.map(ele=>{
                                    storeNameList1.map(item=>{
                                        if(item._id==ele){
                                            justShowingStore.push(item.name);
                                        }
                                    })
                                });
                                this.setState({
                                    justShowingStore
                                },()=>{
                                    console.log(this.state.justShowingStore);
                                })

                            }
                        }else{
                            console.log("获取门店列表出错");
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }else{
                selectedStore.map(ele=>{
                    console.log('this.state.storeNameList');
                    console.log(this.state.storeNameList);
                    this.state.storeNameList.map(item=>{
                        if(item._id==ele){
                            justShowingStore.push(item.name);
                        }
                    })
                });
                this.setState({
                    justShowingStore
                },()=>{
                    console.log(this.state.justShowingStore);
                })
            }
        }
    }

    //把ID转换成汉字显示 科室
    changeToWord1(selectedDpartment){
        let justShowingDepartment=[];
        if(selectedDpartment.length){
            selectedDpartment.map(ele=>{
                this.state.departmentNameList.map(item=>{
                    if(item._id==ele){
                        justShowingDepartment.push(item.name);
                    }
                })
            });
            this.setState({
                justShowingDepartment
            })
        }
    }

    //把ID转换成汉字显示 权限
    changeToWord2(selectedPrivilege){
        let justShowingPrivilege=[];
        if(selectedPrivilege.length){
            selectedPrivilege.map(ele=>{
                // console.log(ele);
                privilegeData.map(item=>{
                    // console.log(item);
                    if(item.son.length){
                        item.son.map(item1=>{
                            if(item1.son.length){
                                item1.son.map(item2=>{
                                    if(item2.keyword==ele){
                                        justShowingPrivilege.push(item2.name);
                                    }
                                })
                            }else{
                                if(item1.keyword==ele){
                                    justShowingPrivilege.push(item1.name);
                                }
                            }
                        })
                    }else{
                        if(item._id==ele){
                            justShowingPrivilege.push(item.name);
                        }
                    }
                })
            })
        }
        this.setState({
            justShowingPrivilege
        },()=>{
            // console.log(this.state.justShowingPrivilege);
        })
    }

    //提成类型变化函数
    handleChangeGetMoneyType(value){
        console.log(value);
        if(value==='5'){
            this.setState({
                canGetMoney:false,
            })
        }else if(value==='1'||value==='2'){
            this.setState({
                canGetMoney:true,
            },()=>{
                this.setState({
                    canGetMoneyByProject:false,
                })
                console.log(this.state.canGetMoneyByProject);
            })
        }else{
            this.setState({
                canGetMoney:true,
            },()=>{
                this.setState({
                    canGetMoneyByProject:true,
                })
                console.log(this.state.canGetMoneyByProject);
            })
        }
    }
    //是否选择了证件类型
    handleSelectIdCard(value){
        console.log(value);
        if(value){
            this.setState({
                isAlreadyChosedIdCard:true,
            })
        }
    }
    render() {
        //科室树结构
        const loop= data =>
            data.map((item) => {
                if(item.mySon){
                    if (item.mySon.length>0&&!item.id) {
                        return (
                            <TreeNode key={item._id} title={item.name}>
                                {item.mySon.map((item1)=>{
                                    return <TreeNode key={item1._id} title={item1.name} className='finalNode'/>;
                                })}
                            </TreeNode>
                        );
                    }else if(!item.id&&item.mySon.length==0){
                        return <TreeNode key={item._id} title={item.name} className='finalNode'/>;
                    }
                }
            });
        const treeNodes = loop(this.state.departmentNameList);
        //权限树结构
        const loop1 = data =>
            data.map((item) => {
                if (item.son.length) {
                    return (
                        <TreeNode key={item.keyword} title={item.name} >
                            {loop1(item.son)}
                        </TreeNode>
                    );
                }else{
                    return <TreeNode key={item.keyword} title={item.name} className='finalNode' disabled={this.state.privilegeOfRole.indexOf(item.keyword)===-1?true:false}/>;
                }
            });
        const treeNodes1 = loop1(this.state.privilegeNameList);

        //console.log(this.state.paths);
        const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16} };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-employee-box'>
                    <div className="show-template">
                        <span>*{this.props.params.employeeId != "0"?"编辑":"新增"}人员信息</span>
                    </div>
                    <h2>基本信息</h2>
                    <div className="my-border"></div>
                    <div >
                        <Row>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="姓名"  >
                                    {getFieldDecorator('username', {
                                        rules: [{ required: true, message: '姓名不能为空' },
                                            { max: 20, message: '最多不能超过20个字' },
                                            { pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9])+$/, message: '请输入中文或英文或数字' },
                                        ]
                                    })(
                                        <Input placeholder="请输入姓名" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="性别"  >
                                    {getFieldDecorator('gender', {
                                        rules: [{ required: true, message: '请选择性别' }]
                                    })(
                                        <Select style={{ width: "100px" }} placeholder="请选择">
                                            <Option value="男">男</Option>
                                            <Option value="女">女</Option>
                                            <Option value='不详'>不详</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="出生年月"  style={{display:'inline-block'}}>
                                    {getFieldDecorator('birthday',{
                                    })(
                                        <DatePicker  format="YYYY-MM-DD" disabledDate={(val) => this.disabledDate(val)} style={{ width: '100%' }} onChange={this.calculateAge.bind(this)}/>
                                    )}
                                </FormItem>
                                <span style={{display:'inline-block',marginTop:'10px'}}>({this.state.age}岁)</span>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="电话号码"  >
                                    {getFieldDecorator('phone', {
                                        rules: [{ required: true, pattern: /^(1[34578]\d{9})$/, message: '请输入正确的手机号' }]
                                    })(
                                        <Input placeholder="请输入电话号码" onChange={this.changUserName.bind(this)} onKeyUp={this.hadnamed.bind(this)}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="岗位属性"  >
                                    {getFieldDecorator('positionAttribution', {
                                        rules: [{ required: true, message: '请选择岗位属性' }]
                                    })(
                                        <Select style={{ width: "100px" }}  placeholder="请选择">
                                            <Option value="全职">全职</Option>
                                            <Option value="兼职">兼职</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label='所属角色组' {...formItemLayout} style={{display:'inline-block'}}>
                                    {getFieldDecorator('belongedRole',{
                                        rules: [{ required: true, type: 'array', message: '请选择角色组！' }],
                                    })(
                                        <Cascader  onChange={this.handleRoleChange.bind(this)} options={this.state.roleList} placeholder="请选择角色组"  />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </div>
                    <div className="related-stores">
                        {this.state.isDoctorRole?<ul style={{justifyContent:'space-between'}}>
                            <div className='add-employee-flex'>
                                <li style={{ color:'rgba(0, 0, 0, 0.85)',fontSize:'14px'}} className="ant-form-item-required">关联科室：</li>
                                {this.state.justShowingDepartment.map((item,i)=>{
                                    if(i<=6) {
                                        return <li key={item}><Link to="">{item}</Link></li>
                                    }
                                })}
                                {this.state.justShowingDepartment.length>=6? <span style={{color:'blue'}}>...</span>:''}
                            </div>
                            <Button icon="plus" size="small" type="primary" onClick={this.showModal1.bind(this)} >关联</Button>
                        </ul>:''}
                    </div>
                    <div className="related-stores">
                        <ul style={{justifyContent:'space-between'}}>
                            <div className='add-employee-flex'>
                                <li style={{ color:'rgba(0, 0, 0, 0.85)',fontSize:'14px'}} className="ant-form-item-required">所属门店：</li>
                                {this.state.justShowingStore.map((item,i)=>{
                                    if(i<=6) {
                                        return <li key={item}><Link to="">{item}</Link></li>
                                    }
                                })}
                                {this.state.selectedStoreList.length>=6? <span style={{color:'blue'}}>...</span>:''}
                            </div>
                            <Button icon="plus" size="small" type="primary" style={{float:'right'}} onClick={this.showModal2.bind(this)}>关联</Button>
                        </ul>
                    </div>
                    <div className="related-stores">
                        {this.state.alreadyChooseRole? <ul style={{justifyContent:'space-between'}}>
                            <div className='add-employee-flex'>
                                <li style={{ color:'rgba(0, 0, 0, 0.85)',fontSize:'14px'}} className="ant-form-item-required">权限分配：</li>
                                {this.state.justShowingPrivilege.map((item,i)=>{
                                    if(i<=6){
                                        return <li key={item}><Link to="">{item}</Link></li>
                                    }
                                })}
                                {this.state.justShowingPrivilege.length>=6? <span style={{color:'blue'}}>...</span>:''}
                            </div>
                            <Button icon="plus" size="small" type="primary" onClick={this.showModal3.bind(this)}>编辑</Button>
                        </ul>:''
                        }
                        <div className='storeRow' style={{ marginTop:'20px' }}>
                            <Row>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="提成类型" >
                                        {getFieldDecorator('bonusType', {
                                        })(
                                            <Select placeholder="请选择提成类型" style={{width:'150px'}} onChange={this.handleChangeGetMoneyType.bind(this)}>
                                                <Option value="1">按项目折后提成</Option>
                                                <Option value="2">按项目原价提成</Option>
                                                <Option value="3">全额提成</Option>
                                                <Option value="4">折后提成</Option>
                                                <Option value="5">无提成</Option>
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                {this.state.canGetMoney&&!this.state.canGetMoneyByProject?<div>
                                    <Col span={6} style={{ display: 'inline-block' }}>
                                        <FormItem {...{ labelCol: { span: 10}, wrapperCol: { span: 14} }} label="设置项目提成" >
                                            {getFieldDecorator('projectBonus1', {
                                                rules: [
                                                    { pattern: /^100$|^(\d|[1-9]\d)$/, message: '请输入0~100的整数' },
                                                ]
                                            })(
                                                <Input addonBefore="挂号费" addonAfter="%" placeholder="请输入0~100的整数" />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem {...{ labelCol: { span: 0 }, wrapperCol: { span: 24 } }} style={{ display: 'inline-block' }}>
                                            {getFieldDecorator('projectBonus2', {
                                                rules: [
                                                    { pattern: /^100$|^(\d|[1-9]\d)$/, message: '请输入0~100的整数' },
                                                ]
                                            })(
                                                <Input addonBefore="药品消费" addonAfter="%" placeholder="请输入0~100的整数" />
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={4}>
                                        <FormItem {...{ labelCol: { span: 0 }, wrapperCol: { span: 24 } }} style={{ display: 'inline-block' }}>
                                            {getFieldDecorator('projectBonus3', {
                                                rules: [
                                                    { pattern: /^100$|^(\d|[1-9]\d)$/, message: '请输入0~100的整数' },
                                                    ]
                                            })(
                                                <Input addonBefore="护理理疗" addonAfter="%" placeholder="请输入0~100的整数" />
                                            )}
                                        </FormItem>
                                    </Col>
                                </div>:''}
                                {this.state.canGetMoney&&this.state.canGetMoneyByProject?<Col span={8}>
                                    <FormItem {...formItemLayout} label="提成比例" >
                                        {getFieldDecorator('bonusScale', {
                                            rules: [{ pattern: /^100$|^(\d|[1-9]\d)$/, message: '请输入0~100的整数' },]
                                        })(
                                            <Input addonAfter="%" placeholder="百位数以内整数" />
                                        )}
                                    </FormItem>
                                </Col>:''}
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="婚姻状况"  >
                                        {getFieldDecorator('isMarried', {

                                        })(
                                            <Select style={{ width: "100px" }}  placeholder="请选择">
                                                <Option value="1">已婚</Option>
                                                <Option value="2">未婚</Option>
                                                <Option value="3">离异</Option>
                                                <Option value="4">丧偶</Option>
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="民族"  >
                                        {getFieldDecorator('nation', {

                                        })(
                                            <Select style={{ width: "100px" }} placeholder="请选择">
                                                {nations.map(item=>{
                                                    return <Option  key={item.id} value={item.id}>{item.name}</Option>
                                                })}
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="负责人邮箱" >
                                        {getFieldDecorator('email', {
                                            rules: [{
                                                type: 'email', message: '请输入正确格式邮箱',
                                            }],
                                        })(
                                            <Input placeholder="请输入负责人邮箱"/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem label='证件类型' {...formItemLayout} >
                                        {getFieldDecorator('cardType',)(
                                            <Select  placeholder='请选择证件类型' style={{width:'100%'}} onChange={this.handleSelectIdCard.bind(this)}>
                                                <Option value='1'>二代身份证</Option>
                                            </Select>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}  >
                                        {getFieldDecorator('identification', {
                                            rules: [{  pattern: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/, message: '请输入18位身份证号' }]
                                        })(
                                            <Input disabled={this.state.isAlreadyChosedIdCard?false:true} placeholder="请输入18位身份证号"/>
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </div>
                        <div className="just-his-input">
                            <FormItem label='人员简介' labelCol={{ span: 3 }} wrapperCol={{ span: 21}}  >
                                {getFieldDecorator('introduction', {
                                    rules: [ { max: 400, message: '最多不超过400字' },
                                        {pattern:/(?!\s+$)(\w|[\u4e00-\u9fa5]){1,400}/,message: '不能全部输入空格'}]
                                })(
                                    <TextArea placeholder="请输入人员简介" autosize={{ minRows: 2, maxRows: 6 }} />
                                )}
                            </FormItem>
                        </div>
                    </div>
                    <h2 style={{marginTop:"28px"}}>帐号信息</h2>
                    <div className="my-border"></div>
                    <div >
                        <Row>
                            <Col span={8}>
                                <FormItem labelCol={{ span: 10 }} wrapperCol={{ span: 14 }} label="登录账号(不可修改)"  >
                                    {getFieldDecorator('uname', {
                                    })(
                                        <Input disabled={true} placeholder="请输入用户名" />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="设置密码"  >
                                    {getFieldDecorator('password', {
                                        rules: [
                                            { required: true, whitespace: true, message: '密码不能为空'},
                                            { min: 6, message: '密码不能少于六位数'},
                                        ]
                                    })(
                                        <Input placeholder="请输入密码" type="password"/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem {...formItemLayout} label="确认密码"  >
                                    {getFieldDecorator('confirmPassword', {
                                        rules: [
                                            { required: true, message: '两次密码输入必须一致' },
                                            { min: 6, message: '确认密码不能少于六位数'},
                                        ]
                                    })(
                                        <Input placeholder="请再次输入密码" type="password" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>

                    {/*关联所属科室模态框*/}
                    <Modal footer={false}
                           title='关联科室'
                           visible={this.state.visible1}
                           onOk={this.handleOk1.bind(this)}
                           onCancel={this.handleCancel1.bind(this)}
                           className="large-model"
                    >
                        <Tree
                            checkable
                            defaultExpandAll
                            onCheck={this.onCheckDepartment.bind(this)}
                            checkedKeys={this.state.checkedKeys}
                            className='privilegeTree'
                        >
                            <TreeNode key={this.state.tree.name} title={this.state.tree.name}>
                                {treeNodes}
                            </TreeNode>
                        </Tree>
                        <p style={{ marginTop: 30 ,textAlign:'right'}}>
                            <Button className='member-button-aa' onClick={this.handleOk1.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                            <Button className='member-button-aa' onClick={this.handleCancel1.bind(this)} style={{ width: 100, marginLeft: 30 }} >取消</Button>
                        </p>
                    </Modal>

                    {/*关联所属门店模态框*/}
                    <Modal footer={false}
                           title={this.state.modalType == 'add' ? '添加' : '编辑'}
                           visible={this.state.visible2}
                           onOk={this.handleOk2.bind(this)}
                           onCancel={this.handleCancel2.bind(this)}
                           className="large-model"
                    >
                        <Checkbox.Group style={{ width: '100%' }} value={this.state.selectedStoreList} onChange={this.handleBelongedStoreChange.bind(this)}>
                            <Row>
                                {
                                    this.state.storeNameList.map(item=>{
                                        return  <Col span={6} key={item.index}><Checkbox disabled={item._id===JSON.parse(sessionStorage.getItem('UserInfo')).shop[0]} value={item._id}>{item.name}</Checkbox></Col>
                                    })
                                }
                            </Row>
                        </Checkbox.Group>
                        <p style={{ marginTop: 30 ,textAlign:'right'}}>
                            <Button className='member-button-aa' onClick={this.handleOk2.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                            <Button className='member-button-aa' onClick={this.handleCancel2.bind(this)} style={{ width: 100, marginLeft: 30 }} >取消</Button>
                        </p>
                    </Modal>

                    {/*关联权限*/}
                    <Modal footer={false}
                           title={this.state.modalType == 'add' ? '添加' : '编辑'}
                           visible={this.state.visible3}
                           onOk={this.handleOk3.bind(this)}
                           onCancel={this.handleCancel3.bind(this)}
                           className="large-model"
                    >
                        <Tree
                            checkable
                            defaultExpandAll
                            onCheck={this.onCheckPrivilege1.bind(this)}
                            checkedKeys={this.state.checkedKeys1}
                            className='privilegeTree'
                        >
                            <TreeNode key={this.state.tree1.keyword} title={this.state.tree1.name}>
                                {treeNodes1}
                            </TreeNode>
                        </Tree>
                        <p style={{ marginTop: 30 ,textAlign:'right'}}>
                            <Button className='member-button-aa' onClick={this.handleOk3.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                            <Button className='member-button-aa' onClick={this.handleCancel3.bind(this)} style={{ width: 100, marginLeft: 30 }} >取消</Button>
                        </p>
                    </Modal>
                </div>
            </div>

        )
    }
}
const AddEmployeeForm = Form.create()(AddEmployee);
export default AddEmployeeForm;
